import 'dart:async';
import 'dart:ui';

import 'package:date_format/date_format.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter/rendering.dart';
import 'package:hitutor/UI/GroupClass/GroupClass.dart';
import 'package:hitutor/UI/HiNote/HiNote.dart';
import 'package:hitutor/UI/Home/Home.dart';
import 'package:hitutor/UI/NoticeAndMessage/DialogReadNotice.dart';
import 'package:hitutor/UI/NoticeAndMessage/NewMessageList.dart';
import 'package:hitutor/UI/NoticeAndMessage/NoticeList.dart';
import 'package:hitutor/Util/DateUtil.dart';
import 'package:hitutor/Util/Global.dart';
import 'package:hitutor/Util/HttpGo.dart';
import 'package:hitutor/Util/MyColor.dart';
import 'package:hitutor/Util/PageUtil.dart';
import 'package:hitutor/Widget/MyButton.dart';
import 'package:hitutor/Widget/MyDialog.dart';
import 'package:hitutor/Widget/MyImage.dart';
import 'package:url_launcher/url_launcher.dart';

class HomeBody extends StatefulWidget {
  @override
  State<StatefulWidget> createState() {
    return HomeBodyState();
  }

  Function(dynamic data) onGetHomePage;
  Function() onToCalendar;

  HomeBody({Key? key, required this.onToCalendar, required this.onGetHomePage}) : super(key: key);
}

class HomeBodyState extends State<HomeBody> {
  ///獲取今日課程
  dynamic firstLesson;

  ///獲取最新消息
  List<dynamic> informationList = [];

  ///獲取公告-判斷有沒有新的公告
  bool haveNewNotice = false;

  ///banner圖
  List<dynamic> bannerDataList = [];

  getHomePage(showLoading) {
    var nowTime = DateTime.now();
    // var nowTime = DateTime(2021, 12, 10);
    String now = getUtcTime(nowTime);
    var endTime = DateTime(nowTime.year, nowTime.month, nowTime.day, 24, 0, 0);
    String end = getUtcTime(endTime);

    HttpGo(context).post("/Information/GetHomePage", {
      "studentId": Global.studentId,
      "beginDateTime": now,
      "endDateTime": end,
      "timeZone": DateTime.now().timeZoneOffset.inMinutes,
    }, (data) {
      getFirstLesson(data["lessonList"] ?? []);
      informationList = data["informationList"];
      haveNewNotice = data["hasNewInformation"];
      bannerDataList = data["carouselList"];
      Global.shareLink = data["shareLink"];
      widget.onGetHomePage.call(data);
      setState(() {});
    }, (code, error) => showToast(error), showLoading: showLoading);
  }

  getFirstLesson(List<dynamic> lessonList) {
    for (var item in lessonList) {
      if (item["lessonState"] == 1) {
        if (firstLesson == null) {
          firstLesson = item;
        } else {
          DateTime today = DateTime.parse(firstLesson["beginTime"]);
          DateTime itemDay = DateTime.parse(item["beginTime"]);
          if (itemDay.isBefore(today)) {
            firstLesson = item;
          }
        }
      }
    }
  }

  ///合併到了getHomePage
  // getTodayClass(showLoading) {
  //   var nowTime = DateTime.now();
  //   String now = getUtcTime(nowTime);
  //   var endTime = DateTime(nowTime.year, nowTime.month, nowTime.day, 24, 0, 0);
  //   String end = getUtcTime(endTime);
  //
  //   HttpGo(context).post("/Lesson/GetBookedLessonList", {"studentId": Global.studentId, "beginDateTime": now, "endDateTime": end},
  //       (data) => getFirstLesson(data["lessonList"] ?? []), (code, error) => showToast(error),
  //       showLoading: showLoading);
  // }

  ///合併到了getHomePage
  // getInformationList() {
  //   HttpGo(context).get("/Information/GetInformationList", {}, (data) {
  //     informationList = data["informationList"];
  //     setState(() {});
  //   }, (code, error) => showToast(error), showLoading: false);
  // }

  ///合併到了getHomePage
  // HasNewInformation() {
  //   HttpGo(context).get("/Information/HasNewInformation?studentId=${Global.studentId}", {}, (data) {
  //     haveNewNotice = data["hasNewInformation"];
  //   }, (code, error) => showToast(error), showLoading: false);
  // }

  @override
  void initState() {
    WidgetsBinding.instance?.addPostFrameCallback((timeStamp) {
      // getTodayClass(false);
      // getInformationList();
      // HasNewInformation();
    });
    super.initState();
  }

  @override
  Widget build(BuildContext context) {
    return SingleChildScrollView(
        child: Column(children: [
      Banner(bannerDataList),
      Container(
          child: Column(children: [
            Visibility(
                visible: firstLesson != null, child: GestureDetector(onTap: widget.onToCalendar, child: ItemTodayClass(firstLesson))),
            Container(height: 16),
            Row(mainAxisAlignment: MainAxisAlignment.spaceAround, children: [
              HomeBtn("five-round-01.png", "HiNote", onTap: () {
                PageUtil().open(context, HiNote());
              }),
              HomeBtn("five-round-02.png", "團班課程", onTap: () {
                PageUtil().open(context, GroupClass());
              }),
              HomeBtn("five-round-03.png", "公告", haveNew: haveNewNotice, onTap: () {
                PageUtil().open(context, NoticeList());
              })
            ]),
            Container(height: 16),
          ]),
          decoration: BoxDecoration(image: DecorationImage(image: AssetImage("images/gplaypattern.png"), fit: BoxFit.cover))),
      NewMsg(informationList)
    ]));
  }
}

class Banner extends StatefulWidget {
  List<dynamic> bannerDataList = [];

  Banner(this.bannerDataList);

  @override
  State<StatefulWidget> createState() {
    return _Banner();
  }
}

class _Banner extends State<Banner> {
  int selectPos = 0;

  @override
  void initState() {
    super.initState();
    // getBanner();
  }

  ///合併到getHomePage
  // getBanner() {
  //   Timer(Duration(milliseconds: 500), () {
  //     HttpGo(context).get("/Information/GetCarouselList", {}, (data) {
  //       bannerDataList = data["carouselList"];
  //       setState(() {});
  //     }, (code, error) {
  //       showToast(error);
  //     });
  //   });
  // }

  @override
  Widget build(BuildContext context) {
    return Stack(children: [
      Container(
          height: MediaQuery.of(context).size.width * 0.55,
          width: double.infinity,
          child: PageView.builder(
              scrollDirection: Axis.horizontal,
              reverse: false,
              controller: PageController(initialPage: 0, viewportFraction: 1, keepPage: true),
              physics: BouncingScrollPhysics(),
              pageSnapping: true,
              onPageChanged: (index) {
                selectPos = index;
                setState(() {});
              },
              itemCount: widget.bannerDataList.length,
              itemBuilder: (BuildContext context, int index) {
                return NetImage(widget.bannerDataList[index]["imgUrl"], height: 176, fit: BoxFit.cover, onTap: () {
                  PageUtil().launchURL(widget.bannerDataList[index]["openUrl"]);
                });
              })),
      Positioned(
          right: 8,
          bottom: 8,
          child: Container(
            height: 22,
            width: 48,
            decoration: Global.getBg(MyColor.Black50, 12),
            alignment: Alignment.center,
            child: Text("${selectPos + 1}/${widget.bannerDataList.length}", style: TextStyle(fontSize: 12, color: MyColor.DD)),
          ))
    ]);
  }
}

class ItemTodayClass extends StatelessWidget {
  dynamic lesson;

  ItemTodayClass(this.lesson);

  @override
  Widget build(BuildContext context) {
    DateTime? begin = getTimeByUtc(lesson["beginTime"]);
    DateTime? end = getTimeByUtc(lesson["endTime"]);
    String beginTime = begin == null ? "" : formatDate(begin, [HH, ":", nn]);
    String endTime = end == null ? "" : formatDate(end, [HH, ":", nn]);
    begin.toString();

    DateTime time = DateTime.parse("2021-12-10T10:00:00Z").toLocal();
    print("getTimeByUtc $time");
    return Container(
      margin: EdgeInsets.fromLTRB(16, 16, 16, 0),
      decoration: Global.getBg(MyColor.Red, 32),
      height: 64,
      alignment: Alignment.center,
      child: Text("$beginTime ~ $endTime (${lesson["teacherName"]})\n${lesson["lessonName"]}",
          textAlign: TextAlign.center, style: TextStyle(fontSize: 16, color: MyColor.White)),
    );
  }
}

class HomeBtn extends StatelessWidget {
  String icon;
  String text;
  Function()? onTap;
  bool haveNew;

  HomeBtn(this.icon, this.text, {this.onTap, this.haveNew = false});

  @override
  Widget build(BuildContext context) {
    return GestureDetector(
        behavior: HitTestBehavior.translucent,
        onTap: onTap,
        child: Column(children: [
          LocalImage(icon,
              width: MediaQuery.of(context).size.width * 0.25,
              height: MediaQuery.of(context).size.width * 0.25,
              padding: EdgeInsets.all(8)),
          Row(
            mainAxisSize: MainAxisSize.min,
            children: [
              Visibility(
                visible: haveNew,
                child: Container(width: 6, height: 6, decoration: Global.getBg(Colors.red, 4), margin: EdgeInsets.symmetric(horizontal: 6)),
              ),
              Text(text, style: TextStyle(fontSize: 16, fontWeight: FontWeight.bold, color: MyColor.Black))
            ],
          )
        ]));
  }
}

class NewMsg extends StatelessWidget {
  List<dynamic> informationList = [];

  NewMsg(this.informationList);

  @override
  Widget build(BuildContext context) {
    return Container(
        color: MyColor.BlueNewMsg,
        padding: EdgeInsets.fromLTRB(8, 16, 0, 16),
        child: Column(children: [
          Row(children: [
            Expanded(child: Text(" 最新消息", style: TextStyle(fontSize: 20, color: MyColor.DD))),
            TextBtn("看更多>>　", style: TextStyle(fontSize: 14, color: MyColor.DD), onTap: () {
              PageUtil().open(context, NewMessageList());
            }),
          ]),
          Container(
              height: 136,
              child: ListView.builder(
                  itemCount: informationList.length > 4 ? 4 : informationList.length,
                  scrollDirection: Axis.horizontal,
                  itemBuilder: (BuildContext context, int index) {
                    return NetImage(informationList[index]["imgUrl"],
                        width: 120, height: 120, fit: BoxFit.cover, padding: EdgeInsets.all(8), onTap: () {
                      if ((informationList[index]["url"] ?? "").isNotEmpty) PageUtil().launchURL(informationList[index]["url"]);
                    });
                  }))
        ]));
  }
}
